package week2;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 1074. 元素和为目标值的子矩阵数量
 * https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target/
 *
 * 执行结果：  通过  显示详情
 *
 * 添加备注
 * 执行用时：134 ms, 在所有 Java 提交中击败了72.47% 的用户
 * 内存消耗：38.7 MB, 在所有 Java 提交中击败了94.38% 的用户
 * 通过测试用例：40 / 40
 * 炫耀一下:
 *
 */
public class Week2NumberOfSubmatricesThatSumToTarget {

    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int sumTarget = 0;
        int lineSize = matrix.length;
        int rowSize = matrix[0].length;

        for(int line = 0; line < lineSize; line++) {
            int[] sum = new int[rowSize];
            for(int cellSize = line; cellSize < lineSize; cellSize++) {
                for(int row = 0; row < rowSize; row++) {
                    sum[row] += matrix[cellSize][row];
                }
                sumTarget += subarraySum(sum, target);
            }
        }

        return sumTarget;
    }

    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, 1);
        int count = 0;
        int pre = 0;
        for(int value : nums) {
            pre += value;
            if(map.containsKey(pre - k)) {
                count += map.get(pre - k);
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
